package com.example.SpringBoot_demo.controller;

import cn.dustlight.captcha.annotations.CodeValue;
import cn.dustlight.captcha.annotations.VerifyCode;

import com.example.SpringBoot_demo.bean.LoginUser;
import com.example.SpringBoot_demo.service.ILoginService;
import com.example.SpringBoot_demo.util.MD5Util;
import com.example.SpringBoot_demo.util.RandomUserId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.Enumeration;
import java.util.logging.Logger;

@Controller
@RequestMapping

public class LoginController {
    @Autowired
    private ILoginService loginService;

    /**
     * 登录验证
      * @param code 验证码
     * @param userName 用户名
     * @param password  密码
     * @param
     * @return
     */
    /**
     * 用户名      sss
     *密码     sss123456
     */

    @PostMapping("login")

    @VerifyCode//检验验证码，正确继续并销毁验证码，错误抛出 VerifyFailException异常
    public String login(@CodeValue String code, String userName, String password, HttpServletRequest request,HttpServletResponse response) throws IOException {

        password= MD5Util.encode(password);
         //MD5加密登录

        LoginUser  loginUser = loginService.login(userName, password);
        System.out.println("验证码 "+code);

        if (loginUser != null) {
            loginUser = loginService.loginById(loginUser.getUserId());//把用户的菜单取到
            if (loginUser.getBlacklist()==0){//非黑名单

            //map.addAttribute("userTreeList", user.getRoleList().get(0).getTreeList());
           // request.setAttribute("users", userService.viewUser());//跳转主页
          //  return "viewUser";
                request.getSession().setAttribute("loginUsers",loginUser);
                request.getSession().setAttribute("userid",loginUser.getUserId());
                request.getSession().setAttribute("userRole",loginUser.getRole());
                request.getSession().setAttribute("userName",loginUser.getUserName());
                response.sendRedirect("index");
                return "index";//登陆成功前往主页
            }else {
                request.setAttribute("errorMsg", "禁止登录！您已被加入黑名单！");

                return "loginErrorMessage";//登录失败返回错误信息
            }

        } else {
            request.setAttribute("errorMsg", "用户名或密码错误！");
            return "loginErrorMessage";//
        }

    }



/**
 * 忘记密码
 * 进行邮箱验证
 * 验证成功
 * 更新用户密码
 *
 * */
    @PostMapping("updatePasswordByEmail")

    public String verify(@CodeValue String code, String email, String userName, String password, String password2, HttpServletResponse response,HttpServletRequest request,HttpSession session) throws IOException {


        System.out.println( " 验证码 "+code);

         Object emailcode =session.getAttribute("emailName");
         String email2=emailcode.toString();

//        String checkCode = request.getParameter("checkCode");
        Object cko = session.getAttribute("simpleCaptcha") ; //验证码对象
        if(cko == null){
            request.setAttribute("errorMsg", "验证码已失效，请重新输入！");
            return "verifyErrorMessage";
        }
        String captcha = cko.toString();
        Date now = new Date();
        Long codeTime = Long.valueOf(session.getAttribute("codeTime")+"");
        if(StringUtils.isEmpty(code) || captcha == null || !(code.equalsIgnoreCase(captcha))) {
            request.setAttribute("errorMsg", "验证码错误！");
            return "verifyErrorMessage";
        } else if ((now.getTime()-codeTime)/1000/60>15) {
            //验证码有效时长为15分钟
            request.setAttribute("errorMsg", "验证码已失效，请重新输入！");
            return "verifyErrorMessage";
        }else {

            session.removeAttribute("simpleCaptcha");
//            response.sendRedirect("updatePasswordByEmail");



            Logger.getGlobal().info(email);
            if (!email.equalsIgnoreCase(email2)) {
                System.out.println("邮箱不一致,input:" + email+ "  sure: " + email2);
               return "verifyErrorMessage";
            }
            else if (!password.equals(password2) ) {
                System.out.println("密码不一致,input:" + password + "  sure: " + password2);
                return "verifyErrorMessage";
            } else {
                password = MD5Util.encode(password);
                loginService.updateUserPassword(email, userName, password, password2);
                return "verifySeccessMsg";
            }

        }
    }



    @PostMapping("verifyEmailToLogin")

    public String verifyEmailToLogin(@CodeValue String code, HttpServletResponse response, HttpServletRequest request, Model model,HttpSession session) throws IOException {


        System.out.println( " 验证码 "+code);

        Object emailcode =session.getAttribute("emailName");
        if (emailcode==null){
            return "loginErrorMessage";
        }
        String email=emailcode.toString();
        if (email==null){
            return "loginErrorMessage";
        }

        LoginUser loginUser=loginService.getUserByEmail(email);


//        String checkCode = request.getParameter("checkCode");
        Object cko = session.getAttribute("simpleCaptcha") ; //验证码对象
        if(cko == null){
            request.setAttribute("errorMsg", "验证码已失效，请重新输入！");
            return "loginErrorMessage";
        }
        String captcha = cko.toString();
        Date now = new Date();
        Long codeTime = Long.valueOf(session.getAttribute("codeTime")+"");
        if(StringUtils.isEmpty(code) || captcha == null || !(code.equalsIgnoreCase(captcha))) {
            request.setAttribute("errorMsg", "验证码错误！");
            return "loginErrorMessage";
        } else if ((now.getTime()-codeTime)/1000/60>15) {
            //验证码有效时长为15分钟
            request.setAttribute("errorMsg", "验证码已失效，请重新输入！");
            return "loginErrorMessage";
        }else {

            session.removeAttribute("simpleCaptcha");
//            response.sendRedirect("updatePasswordByEmail");

            Logger.getGlobal().info(email);

                 if(loginUser!=null){
                     request.getSession().setAttribute("loginUsers",loginUser);
                     request.getSession().setAttribute("userRole",loginUser.getRole());
                     request.getSession().setAttribute("userid",loginUser.getUserId());
                     request.getSession().setAttribute("userName",loginUser.getUserName());
                     response.sendRedirect("index");

                     return "index";
                 }
                 return "loginErrorMessage";

        }
    }

    /**
     * 用户注册
     *
     */


    @PostMapping("registUser")

    public String registUser( String userName, String password,String password2, String userSex, String userPhone, String userAddress,String email)  {

        String userId= RandomUserId.randomId();//
        LoginUser user=loginService.loginById(userId);
        while (user!=null){///已有用户Id重新获取
            userId= RandomUserId.randomId();//
        }
        if (userId==null||userName==null||password==null||userId==" "||userName==""||password==""){

            System.out.println("chucuo");

            return "registErrorMessage";
        }
        LoginUser loginUser=loginService.loginByName(userName);
        if(loginUser !=null){////用户名存在返回注册
            System.out.println("用户名已存在");
            return "registErrorMessage";
        }


        if (!password.equals(password2)){//如果两次输入密码不同，返回注册
            System.out.println("密码不一致");
            return "registErrorMessage";
        }else{
            password= MD5Util.encode(password);///MD5加密
            password2= MD5Util.encode(password2);

            userAddress=userAddress.toString();
            loginService.registUser(userId,userName,password,password2,userSex,userPhone,userAddress,email);



                System.out.println("seccessful");

                return "registSeccessMsg";

        }


    }

    /**
     * 用于退出登录
     * @param request
     * @param session
     * @return  login
     */
    @RequestMapping("logout")
    public String logout(HttpServletRequest request ,HttpSession session,HttpServletResponse response){
        Enumeration em = request.getSession().getAttributeNames();
        while(em.hasMoreElements()){
           request.getSession().removeAttribute(em.nextElement().toString());
      }
        session.invalidate();
        try {
            response.sendRedirect("login");
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "login";
    }




    /*******---------------GetMapping---------------------****/
    @GetMapping("login")
    public String login() { return "login"; }

    @GetMapping("verifyEmailCode")
    public String verifyEmailCode(){ return "verifyEmailCode"; }

    @GetMapping("updatePasswordByEmail")
    public String verify(){ return "updatePasswordByEmail"; }
    //////
    @GetMapping("registUser")
    public String registUser(){return "registUser";}
    @GetMapping("loginErrorMessage")
    public String loginErrorMessage(){
        return "loginErrorMessage";
    }
    @GetMapping("registErrorMessage")
    public String registErrorMessage(){
        return "registErrorMessage";
    }
    @GetMapping("verifyErrorMessage")
    public String verifyErrorMessage(){
        return "verifyErrorMessage";
    }
    @GetMapping("registSeccessMsg")
    public String registSeccessMessage(){
        return "registSeccessMsg";
    }
    @GetMapping( "verifyEmailToLogin")
    public String verifyEmailToLogin(){return "verifyEmailToLogin";}
    @GetMapping( "loginByEmail")
    public String loginByEmail(){return "loginByEmail";}
    /*************************************************************/
}
